import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:get/get.dart';
import 'package:travel/model/theme.dart';
import 'package:travel/model/tourism.dart';
import 'package:travel/routes/index.dart';
import 'package:travel/screen/flutter_screenutil.dart';
import 'package:travel/utils/colors.dart';
import 'package:travel/utils/styles.dart';
import 'package:travel/utils/tools.dart';

class TravelsController extends GetxController {
  late Rx<ThemeTourismModel> model;

  RxBool isLoading = false.obs;

  RxBool hasNext = true.obs;

  RxInt total = 20.obs;

  RxList<TourismModel> data = RxList([]);

  ScrollController scrollController = ScrollController();

  @override
  void onInit() {
    super.onInit();
    model = Rx(ThemeTourismModel(
        imgUrl:
            'https://cdn7.axureshop.com/demo2023/2251242/images/景点主页/u700.png',
        name: '故宫博物馆',
        level: 5,
        point: 4.8,
        evaluate: 3358,
        distance: 1.5,
        price: 50));
    if (Get.arguments != null) {
      model = Rx(Get.arguments['model']);
    }
    initData();
    scrollController.addListener(() {
      if (isLoading.isFalse &&
          scrollController.position.pixels >=
              scrollController.position.maxScrollExtent) {
        isLoading.value = true;
        loadMoreData();
      }
    });
  }

  void initData() {
    data.add(TourismModel(
        imgUrl:
            'https://cdn7.axureshop.com/demo2023/2251242/images/首页_未登录/p0.png',
        describe: '和家人果断在北京续住3天的神仙小院',
        avatar:
            'https://cdn7.axureshop.com/demo2023/2251242/images/首页_未登录/p1.png',
        browse: 1.1,
        nickname: '晚风心里吹'));
    data.add(TourismModel(
        imgUrl:
            'https://cdn7.axureshop.com/demo2023/2251242/images/首页_未登录/p7.png',
        describe: '人少景美“京西小故宫”修缮五年后惊艳开放',
        avatar:
            'https://cdn7.axureshop.com/demo2023/2251242/images/首页_未登录/p8.png',
        browse: 1.3,
        nickname: '唐糖唐来了'));
    data.add(TourismModel(
        imgUrl:
            'https://cdn7.axureshop.com/demo2023/2251242/images/首页_未登录/p2.png',
        describe: '北京海拔2000米的木栈道帝都最高观景平台',
        avatar:
            'https://cdn7.axureshop.com/demo2023/2251242/images/首页_未登录/p3.png',
        browse: 2.1,
        nickname: '美腻的猫'));
    data.add(TourismModel(
        imgUrl:
            'https://cdn7.axureshop.com/demo2023/2251242/images/首页_未登录/p9.png',
        describe: '和家人果断在北京续住3天的神仙小院',
        avatar:
            'https://cdn7.axureshop.com/demo2023/2251242/images/首页_未登录/p10.png',
        browse: 1.1,
        nickname: '小沈阳10'));

    data.add(TourismModel(
        imgUrl:
            'https://cdn7.axureshop.com/demo2023/2251242/images/首页_未登录/p4.png',
        describe: '北京郊区大自然山景私汤山酒店',
        avatar:
            'https://cdn7.axureshop.com/demo2023/2251242/images/首页_未登录/p5.png',
        browse: 1.1,
        nickname: '美美在旅行'));
    data.add(TourismModel(
        imgUrl:
            'https://cdn7.axureshop.com/demo2023/2251242/images/首页_未登录/p11.png',
        describe: '人少景美“京西小故宫”修缮五年后惊艳开放',
        avatar:
            'https://cdn7.axureshop.com/demo2023/2251242/images/首页_未登录/p12.png',
        browse: 1.7,
        nickname: '美美在旅行'));
    data.add(TourismModel(
        imgUrl:
            'https://cdn7.axureshop.com/demo2023/2251242/images/首页_未登录/p6.png',
        describe: '北京周末去哪，找到了人少景美的仙境了！',
        avatar:
            'https://cdn7.axureshop.com/demo2023/2251242/images/首页_未登录/p1.png',
        browse: 3.1,
        nickname: '晚风吹心里'));
    data.add(TourismModel(
        imgUrl:
            'https://cdn7.axureshop.com/demo2023/2251242/images/首页_未登录/p13.png',
        describe: '秋冬京城小奈良动物园里泡温泉',
        avatar:
            'https://cdn7.axureshop.com/demo2023/2251242/images/首页_未登录/p10.png',
        browse: 1.1,
        nickname: '万能夏小姐'));
  }

  Future<void> loadMoreData() {
    return Future.delayed(const Duration(seconds: 1), () {
      if (total.value > data.length) {
        hasNext.value = true;
        isLoading.value = false;
        initData();
        return;
      }
      hasNext.value = false;
      isLoading.value = false;
    });
  }

  @override
  void onClose() {
    super.onClose();
    scrollController.dispose();
    Get.delete();
  }
}

class TravelsView extends GetView<TravelsController> {
  const TravelsView({super.key});

  @override
  Widget build(BuildContext context) {
    return Obx(() => Scaffold(
          backgroundColor: ColorsUtils.backgroundColor,
          body: createdBody(context),
          floatingActionButton: FloatingActionButton(
            foregroundColor: Colors.transparent,
            focusColor: Colors.transparent,
            backgroundColor: Colors.transparent,
            elevation: 0,
            focusElevation: 0,
            highlightElevation: 0,
            hoverElevation: 0,
            hoverColor: Colors.transparent,
            onPressed: () {
              Get.toNamed(RoutePath.attractionsPublish);
            },
            child: CircleAvatar(
              backgroundImage: ToolsUtils.assetImageIcon('u1043.png'),
              backgroundColor: Colors.transparent,
              radius: 30,
              child: ToolsUtils.assetImageSvg('u1044.svg',
                  width: 23.w, height: 24.h),
            ),
          ),
        ));
  }

  Widget createdBody(BuildContext context) {
    return CustomScrollView(
      controller: controller.scrollController,
      slivers: [
        SliverPersistentHeader(
          pinned: true,
          delegate: _SliverCustomHeaderDelegate(
              collapsedHeight: 40.h,
              expandedHeight: 200.h,
              paddingTop: Get.mediaQuery.padding.top,
              coverImgUrl:
                  'https://cdn7.axureshop.com/demo2023/2251242/images/景点主页/u700.png',
              title: controller.model.value.name),
        ),
        SliverPadding(
            padding: EdgeInsets.only(left: 10.w, right: 10.w),
            sliver: SliverToBoxAdapter(
              child: Container(
                padding: EdgeInsets.only(top: 15.h),
                decoration: const BoxDecoration(color: Colors.white),
                child: StaggeredGrid.count(
                  crossAxisCount: 2,
                  crossAxisSpacing: 10.w,
                  mainAxisSpacing: 5.h,
                  children: controller.data
                      .map((e) => Column(
                            children: [
                              Container(
                                height: 130.h,
                                decoration: BoxDecoration(
                                    borderRadius: BorderRadius.only(
                                        topLeft: Radius.circular(8.w),
                                        topRight: Radius.circular(8.w)),
                                    image: DecorationImage(
                                        alignment: Alignment.topLeft,
                                        fit: BoxFit.fill,
                                        filterQuality: FilterQuality.high,
                                        image: NetworkImage(
                                          e.imgUrl,
                                        ))),
                              ),
                              Container(
                                margin: EdgeInsets.symmetric(vertical: 8.w),
                                alignment: Alignment.centerLeft,
                                child: Text(
                                  e.describe,
                                  overflow: TextOverflow.ellipsis,
                                  maxLines: 2,
                                  style: StylesUtils.customTextStyle(
                                      fontWeight: FontWeight.w700,
                                      color: ColorsUtils.color3333,
                                      lineHeight: 1.3.h),
                                ),
                              ),
                              Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                children: [
                                  Expanded(
                                      child: Text.rich(
                                    TextSpan(children: [
                                      WidgetSpan(
                                          child: CircleAvatar(
                                        radius: 10,
                                        backgroundImage: NetworkImage(e.avatar),
                                      )),
                                      TextSpan(
                                          text: '  ${e.nickname}',
                                          style: StylesUtils.customTextStyle(
                                              color: ColorsUtils.color6666,
                                              fontSize: 13.sp))
                                    ]),
                                    maxLines: 1,
                                    overflow: TextOverflow.ellipsis,
                                  )),
                                  Text.rich(TextSpan(children: [
                                    WidgetSpan(
                                        child: Icon(
                                            Icons.remove_red_eye_outlined,
                                            color: ColorsUtils
                                                .parseColorFromHexString(
                                                    ColorsUtils.color3333),
                                            size: 15.w),
                                        alignment: PlaceholderAlignment.middle),
                                    TextSpan(
                                        text: '${e.browse}万',
                                        style: StylesUtils.customTextStyle(
                                            color: ColorsUtils.color6666,
                                            fontSize: 13.sp))
                                  ]))
                                ],
                              )
                            ],
                          ))
                      .toList(),
                ),
              ),
            )),
        if (controller.hasNext.isFalse)
          SliverToBoxAdapter(child: noDataBottom())
        else if (controller.isLoading.isTrue)
          SliverToBoxAdapter(child: renderBottom())
      ],
    );
  }

  Widget noDataBottom() {
    return Container(
      padding: EdgeInsets.symmetric(vertical: 15.h),
      alignment: Alignment.center,
      child: Text(
        '已经到底',
        style: StylesUtils.customTextStyle(
            fontSize: 15.sp, color: ColorsUtils.color3333),
      ),
    );
  }

  Widget renderBottom() {
    if (controller.isLoading.isTrue) {
      return Container(
        padding: EdgeInsets.symmetric(vertical: 15.h),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text('努力加载中...',
                style: StylesUtils.customTextStyle(
                    fontSize: 15.sp, color: ColorsUtils.color3333)),
            const Padding(padding: EdgeInsets.only(left: 10)),
            SizedBox(
              width: 20,
              height: 20,
              child: CircularProgressIndicator(
                strokeWidth: 3,
                color:
                    ColorsUtils.parseColorFromHexString(ColorsUtils.color3478),
              ),
            ),
          ],
        ),
      );
    }
    return Container(
      padding: EdgeInsets.symmetric(vertical: 15.h),
      alignment: Alignment.center,
      child: Text('上拉加载更多',
          style: StylesUtils.customTextStyle(
              color: ColorsUtils.color3333, fontSize: 15.sp)),
    );
  }
}

class _SliverCustomHeaderDelegate extends SliverPersistentHeaderDelegate {
  final double collapsedHeight;
  final double expandedHeight;
  final double paddingTop;
  final String coverImgUrl;
  final String title;
  String statusBarMode = 'light';

  _SliverCustomHeaderDelegate(
      {required this.collapsedHeight,
      required this.expandedHeight,
      required this.paddingTop,
      required this.coverImgUrl,
      required this.title});

  @override
  double get minExtent => collapsedHeight + paddingTop;

  @override
  double get maxExtent => expandedHeight;

  @override
  bool shouldRebuild(SliverPersistentHeaderDelegate oldDelegate) {
    return true;
  }

  void updateStatusBarBrightness(shrinkOffset) {
    if (shrinkOffset > 50) {
      SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
        statusBarBrightness: Brightness.dark,
        statusBarIconBrightness: Brightness.dark,
      ));
    } else {
      SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
        statusBarBrightness: Brightness.light,
        statusBarIconBrightness: Brightness.light,
      ));
    }
  }

  Color makeStickyHeaderBgColor(shrinkOffset) {
    final int alpha =
        (shrinkOffset / (maxExtent - minExtent) * 255).clamp(0, 255).toInt();
    return Color.fromARGB(alpha, 255, 255, 255);
  }

  Color makeStickyHeaderTextColor(shrinkOffset, isIcon) {
    if (shrinkOffset <= 30) {
      return isIcon ? Colors.white : Colors.transparent;
    } else {
      final int alpha =
          (shrinkOffset / (maxExtent - minExtent) * 255).clamp(0, 255).toInt();
      return Color.fromARGB(alpha, 0, 0, 0);
    }
  }

  @override
  Widget build(
      BuildContext context, double shrinkOffset, bool overlapsContent) {
    updateStatusBarBrightness(shrinkOffset);
    return SizedBox(
      height: maxExtent,
      child: Stack(
        fit: StackFit.expand,
        children: <Widget>[
          Container(
              decoration: BoxDecoration(
                  image: DecorationImage(
                      image: NetworkImage(coverImgUrl),
                      fit: BoxFit.cover,
                      colorFilter: ColorFilter.mode(
                          ColorsUtils.rgba(0, 0, 0, 0.447058823529412),
                          BlendMode.srcOver))),
              child: Stack(
                children: [
                  Positioned(
                      top: 0,
                      right: 0,
                      left: 0,
                      child: Container(
                        padding:
                            EdgeInsets.only(left: 15.w, right: 15.w, top: 80.h),
                        alignment: Alignment.centerLeft,
                        child: Text(
                          title,
                          style: StylesUtils.customTextStyle(fontSize: 20.sp),
                        ),
                      )),
                  Positioned(
                      top: 100.h,
                      left: 0,
                      right: 0,
                      child: Container(
                        alignment: Alignment.centerLeft,
                        padding:
                            EdgeInsets.only(left: 15.w, right: 15.w, top: 20.h),
                        child: Row(
                          children: [
                            Icon(
                              Icons.location_on_outlined,
                              size: 15.sp,
                              color: Colors.white,
                            ),
                            Text(
                              ' 北京市东城区景山前街4号',
                              style:
                                  StylesUtils.customTextStyle(fontSize: 13.sp),
                            )
                          ],
                        ),
                      )),
                  Positioned(
                    bottom: 0,
                    right: 0,
                    left: 0,
                    child: Container(
                      width: double.infinity,
                      padding: EdgeInsets.symmetric(
                          vertical: 15.h, horizontal: 15.w),
                      decoration: BoxDecoration(
                          color: Colors.white,
                          borderRadius: BorderRadius.only(
                              topLeft: Radius.circular(15.w),
                              topRight: Radius.circular(15.w))),
                      child: Wrap(
                        spacing: 5.w,
                        crossAxisAlignment: WrapCrossAlignment.center,
                        children: [
                          Text(
                            '达人游记',
                            style: StylesUtils.customTextStyle(
                                fontWeight: FontWeight.w700,
                                fontSize: 22.sp,
                                color: ColorsUtils.color3333),
                          ),
                        ],
                      ),
                    ),
                  )
                ],
              )),
          Positioned(
            top: 0,
            left: 0,
            right: 0,
            child: Container(
              color: makeStickyHeaderBgColor(shrinkOffset),
              child: SafeArea(
                bottom: false,
                child: SizedBox(
                  height: collapsedHeight,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      IconButton(
                        icon: Icon(
                          Icons.arrow_back_ios,
                          color: makeStickyHeaderTextColor(shrinkOffset, true),
                        ),
                        onPressed: () => Get.back(),
                      ),
                      Expanded(
                          child: Center(
                              child: Text(
                        title,
                        style: TextStyle(
                          fontSize: 18.sp,
                          fontWeight: FontWeight.w500,
                          color: makeStickyHeaderTextColor(shrinkOffset, false),
                        ),
                      ))),
                      IconButton(
                        icon: Icon(
                          Icons.share,
                          color: makeStickyHeaderTextColor(shrinkOffset, true),
                        ),
                        onPressed: () async {
                          // int? index = await ToolsUtils.openShare(context);
                        },
                      ),
                    ],
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
